const Excel = require('exceljs');
const moment = require('moment');
const path = require('path');

class ExcelUtil {
    constructor() {
        this._workbook = new Excel.Workbook();
        this._workbook.creator = 'xsb-admin';
        this._workbook.lastModifiedBy = 'xsb-admin';
        this._workbook.created = new Date();
        this._workbook.modified = new Date();
        this._workbook.lastPrinted = new Date();
        this.views = [{
            x: 0,
            y: 0,
            width: 10000,
            height: 20000,
            firstSheet: 0,
            activeTab: 1,
            horizontalCentered: true,
            fitToWidth: true,
            visibility: 'visible'
        }];
    }

    addSheet(sheet) {
        this._worksheet = this._workbook.addWorksheet(sheet, { properties: { tabColor: { argb: 'FFC0000' } } });
    }
    initFeedBackExcel(date) {
        this._name = `${moment(date).format('YYYY-MM-DD')} 用户反馈`;
        const columns = [
            { header: 'BUG', key: 'bug', width: 20 },
            { header: '平台', key: 'client', width: 10 },
            { header: 'U-Agent', key: 'ua', width: 40, outlineLevel: 1 },
            { header: 'UID', key: 'uid', width: 10, outlineLevel: 1 },
            { header: '联系方式', key: 'mobile', width: 15, outlineLevel: 1 },
            { header: '反馈时间', key: 'time', width: 20, outlineLevel: 1 }
        ];
        this.buildSheet(this._name, columns);
    }

    buildSheet(name, columns) {
        this._name = name;
        this._path = path.join(process.cwd(), this._name + '.xlsx');
        this.addSheet(`${name}`);
        this._worksheet.columns = columns;
    }
    addRow(row) {
        this._worksheet.addRow(row);
    }

    export() {
        return this._workbook.xlsx.writeBuffer()
        .then((data) => {
            return data;
        });
    }
}

module.exports = ExcelUtil;
